<script setup lang="ts">
import * as echarts from 'echarts'
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { reqSeller } from '@/api/screenD'
import purplePassion from '@/views/screenD/static/theme/purple-passion.json'

// 初始化EChartInstance
let EChartInstance: any = null
let allData = ref<any>({})
const seller_ref = ref<HTMLElement>()
let currentPage = ref<number>(1)
const totalPage = ref(0)
let timer: any = null
onMounted(() => {
  initChart()
  getData()
  timerCreate()
})
const timerCreate = () => {
  if (timer != null) {
    clearInterval(timer)
  }
  timer = setInterval(() => {
    currentPage.value++
    if (currentPage.value > totalPage.value) {
      currentPage.value = 1
    }
    updateChart()
  }, 2000)
}
onBeforeUnmount(() => {
  clearInterval(timer)
})
const initChart = () => {
  // 设置主题
  echarts.registerTheme('purple-passion', purplePassion)
  EChartInstance = echarts.init(seller_ref.value, 'purple-passion')
  // 鼠标悬停停止换页
  EChartInstance.on('mouseover', () => {
    clearInterval(timer)
  })
  EChartInstance.on('mouseout', () => {
    timerCreate()
  })
}
// 获取数据
const getData = async () => {
  const ret = await reqSeller()
  allData.value = ret
  allData.value.sort((a: any, b: any) => {
    return a.value - b.value //从小到大排序
  })
  // 每五一页
  totalPage.value =
    allData.value.length % 5 === 0
      ? allData.value.length / 5
      : Math.ceil(allData.value.length / 5)
  updateChart()
}
// 更新图表
const updateChart = () => {
  const start = (currentPage.value - 1) * 5
  const end = currentPage.value * 5
  const showData = allData.value.slice(start, end)
  const sellerName = showData.map((item: any) => item.name)
  const sellerValue = showData.map((item: any) => item.value)
  const option = {
    title: {
      text: '▋ 商家销售统计',
      textStyle: {
        fontSize: 33,
      },
      left: 10,
      top: 20,
    },
    //直角坐标系内绘图网格
    grid: {
      top: '20%',
      left: '6%',
      right: '6%',
      bottom: '3%',
      containLabel: true, //grid 区域是否包含坐标轴的刻度标签。
    },
    xAxis: { type: 'value' },
    yAxis: {
      type: 'category',
      data: sellerName,
    },
    series: [
      {
        type: 'bar',
        data: sellerValue,
      },
    ],
  }
  EChartInstance.setOption(option)
}
</script>

<template>
  <div class="com-container">
    <div class="com-chart" ref="seller_ref"></div>
  </div>
</template>

<style scoped lang="scss">
.com-chart {
  width: 100%;
  height: 100%;
}

.com-container {
  width: 100%;
  height: 100%;
}
</style>
<style lang="scss">
canvas {
  border-radius: 20px;
}
</style>
